<template>
  <div class="app-container">
    <el-form :model="form" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="168px">
      <el-form-item label="门店" prop="shopId">
        <el-select
          v-model="form.shopId"
          placeholder="请选择门店"
          clearable
          :style="{width: '100%'}" disabled>
          <el-option
            v-for="(item, index) in shopList"
            :key="index"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户" prop="customerId">
        <el-select v-model="form.customerId" placeholder="全部" clearable :style="{width: '100%'}" disabled>
          <el-option v-for="(item, index) in customer" :key="index" :label="item.name"
                     :value="item.id" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="销售员" prop="salerId">
        <el-select v-model="form.salerId" placeholder="全部" clearable :style="{width: '100%'}" disabled>
          <el-option v-for="(item, index) in user" :key="index" :label="item.userName"
                     :value="item.userId" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="付款时间" prop="paymentDate" >
        <el-date-picker clearable
                        v-model="form.paymentDate"
                        type="date"
                        style="width: 150px"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择付款时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="销售单号" prop="saleOrderId">
        <el-input v-model="form.saleOrderId" placeholder="请输入销售单号" clearable size="small"
                  style="width: 240px" @focus="showOrderSelectDialog" :disabled="isOrder"></el-input>
      </el-form-item><br>
      <el-form-item label="状态" prop="status" v-if="this.$route.query.id">
        <div>
          <span>{{ form.status == 0 ? '未审核' : form.status == 3 ? '审核通过' : '审核拒绝'}}</span>
        </div>
      </el-form-item><br>
      <el-form-item label="操作人" prop="createBy" v-if="this.$route.query.id">
        <div>
          <span>{{ form.createBy }}</span>
        </div>
      </el-form-item>
      <el-form-item label="操作时间" prop="createTime" v-if="this.$route.query.id">
        <div>
          <span>{{ parseTime(form.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </div>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="tblSaleOutSheetDetailList" height="500" >
      <el-table-column label="商品编号" prop="baseDataProduct.code" align="center" width="100" show-overflow-tooltip/>
      <el-table-column label="商品名称" prop="baseDataProduct.name" align="center" width="200"/>
      <el-table-column label="单位" prop="baseDataProduct.unit" align="center" />
      <el-table-column label="规格" prop="baseDataProduct.spec" align="center" />
      <el-table-column label="商品类目" prop="baseDataProduct.baseDataProductCategory.name" align="center" />
      <el-table-column label="商品品牌" prop="baseDataProduct.baseDataProductBrand.name" align="center" />
      <el-table-column label="库存数量" prop="baseDataProduct.tblProductStock.stockNum" align="center" />
      <el-table-column label="销售数量" prop="saleOrderNum" align="center" />
      <el-table-column label="出库数量" prop="orderNum" align="center" >
        <template slot-scope="scope">
          <el-input v-model="scope.row.orderNum" @input="getAmount()"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="description" align="center"  width="120">
        <template slot-scope="scope">
          <el-input v-model="scope.row.description" />
        </template>
      </el-table-column>
    </el-table>
    <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px;text-align: right">
      <label >备注： </label>
      <textarea v-model="form.description" style="width: 90%;height: 50px;margin-top: 10px;margin-left: 10px;margin-bottom: 10px;border-radius: 5px;vertical-align:middle;border: 1px gainsboro solid"/>
    </div>

    <div slot="footer" class="dialog-footer" style="text-align: center;margin: 5px">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>


    <!-- 引入订单选择弹窗 -->
    <OrderSelectDialog ref="orderSelectDialog" @order-selected="handleOrderSelected" />

  </div>
</template>

<script>
import {addSheet, getSheet, listSheet, updateSheet} from "@/api/system/outsheet";
import { getOrder} from "@/api/system/order";
import {center, customer} from "@/api/system/order";
import { listUser } from "@/api/system/user";
import {parseTime} from "../../../utils/ruoyi";
import OrderSelectDialog from "@/views/system/SaleOutSheet/OrderSelectDialog.vue";
import {listStock} from "@/api/system/stock";
import {listShop} from "../../../api/system/Shop";

export default {
  name: "orderAdd",
  components: {
    OrderSelectDialog,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      payTypes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售数量
      orderNum: null,
      // 赠品数量
      giftNum: null,
      // 含税总金额
      taxAmount: null,
      // 商品下拉框
      productList: [],
      // 仓库下拉框
      ck: [],
      // 用户(审核人、操作人、销售员)下拉框
      user: [],
      // 客户下拉框
      customer: [],
      //销售出库单详情表格数据
      tblSaleOutSheetDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 销售数量
      num: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        scName: null,
        customerName: null,
        salerName: null,
      },
      // 表单参数
      form: {},
      // 根据订单ID查询订单支付方式
      payType: {
        orderId: null,
      },
      // 表单校验
      rules: {
        code: [
          { required: true, message: "编号不能为空", trigger: "blur" }
        ],
      },
      //出库表ID数据
      OutSheetAllList:[],
      //出库详情表ID数据
      OutSheetDetailAllList:[],
      //商品库存id
      productStockAllList:[],
      //销售单号
      isOrder: false,

      shopList: [], // 门店列表
    };
  },
  created() {
    this.getList();
  },
  methods: {
    parseTime,
    /** 查询订单详情 */
    getList() {
      this.loading = false;
      customer(this.customer).then(response => {
        this.customer = response.rows;
      });
      center(this.ck).then(response => {
        this.ck = response.rows;
      });
      listUser(this.user).then(response => {
        this.user = response.rows;
      });
      this.OutSheetDetailAllList=[];
      listSheet({}).then(response => {
        this.OutSheetDetailAllList = response.rows;
        let list=response.rows;
        for (var i=0;i<list.length;i++){
          this.OutSheetAllList.push(list[i].id);
        }
      });
      listShop().then(response => {
        this.shopList = response.rows;
      });
      if (this.$route.query.id!=null){
        this.isOrder = true;
        this.selectOrder(this.$route.query.id);
      }
      this.getAmount();
    },
    /** 查询订单详情 */
    selectOrder(id) {
      getSheet(id).then(response => {
        // 订单赋值
        this.form = response.data;
        this.form.salerId = parseInt(this.form.salerId)
        this.tblSaleOutSheetDetailList = response.data.tblSaleOutSheetDetailList;
        //显示商品销售数量
        getOrder(this.form.saleOrderId).then(response => {
          for (let i = 0; i < response.data.tblSaleOrderDetailList.length; i++) {
            this.tblSaleOutSheetDetailList[i].saleOrderNum = response.data.tblSaleOrderDetailList[i].orderNum;
            this.selectProductStockList(this.form.scId, this.tblSaleOutSheetDetailList[i])
          }
        });
        //状态值颜色判断
        if (response.data.status == 0) {
          this.statusColor = "rgb(100, 100, 100)";
        } else if (response.data.status == 3) {
          this.statusColor = "rgb(82, 196, 26)";
        } else {
          this.statusColor = "rgb(255, 0, 0)";
        }
      });
    },
    //获取库存列表
    selectProductStockList(scId, tblSaleOutSheetDetail) {
      listStock({scId,productId:tblSaleOutSheetDetail.productId}).then(response => {
        // this.productStock = response.rows[0];
        if (response.rows.length === 0){
          tblSaleOutSheetDetail.baseDataProduct.tblProductStock = {
            id: generateUniqueId(this.productStockAllList),
            productId: tblSaleOutSheetDetail.productId,
            scId: scId,
            stockNum: 0,
            taxPrice: tblSaleOutSheetDetail.taxPrice,
            taxAmount: 0,
          }
        }
        tblSaleOutSheetDetail.baseDataProduct.tblProductStock = response.rows[0];
      });
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    // 修改价格，折扣随之变化
    getDiscountRate(row){
      if (row.taxPrice && row.oriPrice) {
        row.discountRate = ((row.taxPrice / row.oriPrice) * 100).toFixed(2);
        this.getAmount();
      }
    },
    // 修改折扣，价格随之变化
    getTaxPrice(row){
      if (row.oriPrice) {
        row.taxPrice = row.oriPrice * (row.discountRate / 100).toFixed(2);
        this.getAmount();
      }
    },
    getAmount(){
      this.getOrderNum();
      this.getGiftNum();
      this.getTaxAmount();
    },
    // 取消按钮
    cancel() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.back();
    },
    // 循环遍历，获取销售总数量
    getOrderNum() {
      let sum = 0;
      for (let i = 0; i < this.tblSaleOutSheetDetailList.length; i++) {
        sum += parseInt(this.tblSaleOutSheetDetailList[i].orderNum);
      }
      if (sum >= 0){
        this.form.totalNum = sum;
      }else {
        this.form.totalNum = 0;
      }
    },
    // 循环遍历，获取赠品总数量
    getGiftNum() {
      let sum = 0;
      for (let i = 0; i < this.tblSaleOutSheetDetailList.length; i++) {
        if (this.tblSaleOutSheetDetailList[i].isGift == 1){
          sum += this.tblSaleOutSheetDetailList[i].orderNum;
        }
      }
      this.form.totalGiftNum = sum;
    },
    // 循环遍历，获取含税总金额
    getTaxAmount() {
      let sum = 0;
      for (let i = 0; i < this.tblSaleOutSheetDetailList.length; i++) {
        sum += this.tblSaleOutSheetDetailList[i].taxPrice * this.tblSaleOutSheetDetailList[i].orderNum;
      }
      this.form.totalAmount = sum;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        available: null,
        description: null,
        createBy: null,
        createById: null,
        createTime: null,
        updateBy: null,
        updateById: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    // 销售订单弹窗
    showOrderSelectDialog() {
      this.$refs.orderSelectDialog.show();
    },
    handleOrderSelected(order) {
      // 将弹窗中选中的数据，进行赋值
      getOrder(order.id).then(response => {
        this.form = response.data;
        this.form.salerId = parseInt(this.form.salerId)
        this.form.saleOrderId = order.id;
        this.tblSaleOutSheetDetailList = response.data.tblSaleOrderDetailList;
        for (let i = 0; i < response.data.tblSaleOrderDetailList.length; i++) {
          this.tblSaleOutSheetDetailList[i].id = generateUniqueId(this.OutSheetDetailAllList);
          this.tblSaleOutSheetDetailList[i].saleOrderNum = response.data.tblSaleOrderDetailList[i].orderNum;
          this.tblSaleOutSheetDetailList[i].orderNum = response.data.tblSaleOrderDetailList[i].orderNum;
          this.tblSaleOutSheetDetailList[i].orderNo = response.data.tblSaleOrderDetailList.length + 1
          this.selectProductStockList(this.form.scId, this.tblSaleOutSheetDetailList[i])
        }
        this.getAmount();
        console.log(this.tblSaleOutSheetDetailList)
      });
    },
    /** 提交按钮 */
    submitForm() {
      for (let i = 0; i < this.tblSaleOutSheetDetailList.length; i++) {
        console.log(this.tblSaleOutSheetDetailList[i].orderNum+"?"+this.tblSaleOutSheetDetailList[i].saleOrderNum)
        if (this.tblSaleOutSheetDetailList[i].orderNum == null){
          this.$modal.msgError("第"+(i+1)+"行数据的出库数量不能为空");
          return;
        }
        if (this.tblSaleOutSheetDetailList[i].orderNum <= 0){
          this.$modal.msgError("第" + (i + 1) + "行数据的出库数量不能为0或负数");
          return;
        }
        if (parseInt(this.tblSaleOutSheetDetailList[i].orderNum) > parseInt(this.tblSaleOutSheetDetailList[i].saleOrderNum)){
          this.$modal.msgError("第"+(i+1)+"行数据的出库数量不能大于销售订单数量");
          return;
        }
      }
      if (this.$route.query.id) {
        this.form.tblSaleOutSheetDetailList=this.tblSaleOutSheetDetailList;
        updateSheet(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.$store.dispatch("tagsView/delView", this.$route);
          this.$router.back();
        });
      }else{
        const newId = generateUniqueId(this.OutSheetAllList);
        var orderCode = getOrderCode(this.OutSheetDetailAllList);
        this.form.id=newId;
        this.form.code=orderCode;
        for (let i = 0; i < this.tblSaleOutSheetDetailList.length; i++) {
          this.tblSaleOutSheetDetailList[i].sheetId=newId;
        }
        this.form.tblSaleOutSheetDetailList=this.tblSaleOutSheetDetailList;
        this.form.createBy="系统管理员";
        this.form.createById="1";
        this.form.updateBy="系统管理员";
        this.form.updateById="1";
        this.form.status=0;
        this.form.approveBy=null;
        this.form.approveTime=null;
        this.form.settleStatus=0;

        console.log(this.form);
        addSheet(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.$store.dispatch("tagsView/delView", this.$route);
          this.$router.back();
        });
      }
    }
  },
  beforeRouteLeave(to, from, next) {
    // 设置一个标志，表示需要刷新数据
    to.meta.xsck = true;
    next();
  },
};

// ID生成
function generateUniqueId(existingIds) {
  const prefix = '18';
  const length = 19 - prefix.length;
  const characters = '0123456789';
  let uniqueId;

  do {
    uniqueId = prefix;
    for (let i = 0; i < length; i++) {
      uniqueId += characters.charAt(Math.floor(Math.random() * characters.length));
    }
  } while (existingIds.includes(uniqueId));

  return uniqueId;
}


//单号生成
function getOrderCode(list) {
  var date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1, // 月份是从0开始的
    day = date.getDate();

// 如果月份或日期是个位数，在前面补0
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;

  var time=year + '' + month + '' + day

  let type="XSCK";  //销售出库
  var code=time+'0000000'
  var str1=code.slice(0,7)
  var str2=code.slice(7,)

  if (str2.slice(0,1)=="0"){
    str1=code.slice(0,6)
    str2=code.slice(6,)

    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(6,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(6,)
        }
      }
    }
  }else {
    for (var i=0;i<list.length;i++){
      let listCode=list[i].code.slice(4,);
      if (listCode.slice(0, 8)===time){
        if (parseInt(listCode.slice(7,))>parseInt(str2)){
          code=listCode;
          str2=code.slice(7,)
        }
      }
    }
  }

  code=type+str1+(parseInt(str2)+1)

  return code.toString();
}
</script>
